#!/usr/bin/env bash
# Copyright (c) 2022 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0


readonly BALL_TYPES="\
tar tgz zip jar rpm \
tar.gz tar.bz2 tar.xz \
xz\
"

suffix() {
    local t="" t1="$1" t2="$2"
    case "$t1" in
        "tar"|"tgz"|"zip"|"jar"|"rpm")
            t="$t1"
            ;;
        "gz"|"bz2"|"xz")
            if [ "$t2" = "tar" ]; then
                t="$t2.$t1"
            else
                case "$t1" in
                    "xz")
                        t="$t1"
                        ;;
                esac
            fi
            ;;
    esac
    echo "$t"
}

# uncompress suffix ball
uncompress() {
    local t="$1"
    local f="$2"

    case "$t" in
        "tar")
            tar -xf "$f"
            ;;
        "tgz"|"tar.gz")
            tar -zxf "$f"
            ;;
        "zip")
            unzip -q "$f"
            ;;
        "tar.bz2")
            tar -jxf "$f"
            ;;
        "tar.xz")
            tar -Jxf "$f"
            ;;
        "xz")
            xz -d "$f"
            ;;
        "jar")
            unzip -q "$f" -d "${f%.*}"
            ;;
        "rpm")
            rpm2cpio "$f" | cpio -id --quiet
            ;;
        *)
            echo "\"$t\" is not supported now"
            ;;
    esac
}

# main ball
main() {
    local f="$1"
    if [[ -z "$f" || ! -e "$f" ]]; then
        echo "\"$f\" is not file"; exit
    fi
    local t="" t1="" t2=""
    t1=${f##*.}
    if [[ -z "$t1" || "$t1" = "$f" ]]; then
        echo "\"$f\" without type suffix"; exit
    fi
    t=${f%.*}
    t2=${t##*.}
    t=$(suffix "$t1" "$t2")
    if [ -z "$t" ]; then
        echo "\"$f\" suffix is not supported"
        echo "\"$BALL_TYPES\" are supported"
        exit
    fi
    uncompress "$t" "$f"
}

main "$@"
